package com.grammer.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    private int j;
    private Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        TestLock testLock = new TestLock();
        for (int i = 0; i < 2; i++) {
            new Thread(testLock.new Adder()).start();
            new Thread(testLock.new Subtractor()).start();
        }
    }

    private class Subtractor implements Runnable {
        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    System.out.println("j--=" + j--);
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    private class Adder implements Runnable {
        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    System.out.println("j++=" + j++);
                } finally {
                    lock.unlock();
                }

            }
        }
    }
}
